<template>
  <div class="row g-5 g-xl-10 mb-xl-10 mb-5">
    <!-- 基础信息卡片 -->
    <div class="col-md-6 col-lg-6 col-xl-6 col-xxl-3 mb-md-5 mb-xl-10">
      <ImportInfoWidget
        class="h-md-50 mb-xl-10 mb-5"
        :latest-import-date="baseInfo.latestImportDate"
        :total-commits="baseInfo.totalCommits"
        bg-color="#F1416C"
        :chart-size="70"
        :current-month-commits="baseInfo.currentMonthCommits"
        :previous-month-commits="baseInfo.previousMonthCommits"
      />
      <RepoCountWidget
        class="h-lg-50"
        :beijing-count="baseInfo.beijingRepoCount"
        :chengdu-count="baseInfo.chengduRepoCount"
        :chart-size="70"
      />
    </div>
    <div class="col-md-6 col-lg-6 col-xl-6 col-xxl-3 mb-md-5 mb-xl-10">
      <CommitRepoWidget
        class="h-md-50 mb-xl-10 mb-5"
        :repos-with-commits="baseInfo.reposWithCommits"
        :repos-with-commits-last-month="baseInfo.reposWithCommitsLastMonth"
        :chart-size="70"
      />
      <EngineerStatsWidget
        class="h-lg-50"
        :total-engineers="baseInfo.totalEngineers"
        :backend-engineers="baseInfo.backendEngineers"
        :frontend-engineers="baseInfo.frontendEngineers"
        :chart-size="70"
      />
    </div>
    <div class="col-xxl-6">
      <!-- Widget5 placeholder for decoration -->
      <DashboardIllustrationWidget class="h-md-100" />
    </div>

    <!-- Add new row for ActiveRepositoryTop10 -->
    <div class="col-12">
      <ActiveRepositoryTop10 />
    </div>

    <!-- 历史提交Top5卡片 -->
    <div class="col-md-7 col-lg-7 col-xl-7 col-xxl-7 mb-md-5 mb-xl-10">
      <HistoricalTop5 />
    </div>
    <!-- 最近一个月提交Top5卡片 -->
    <div class="col-md-5 col-lg-5 col-xl-5 col-xxl-5 mb-md-5 mb-xl-10">
      <LastMonthTop5 />
    </div>
    <!-- 组织架构卡片 -->
    <div class="col-md-6 col-lg-6 col-xl-6 col-xxl-6 mb-md-5 mb-xl-10">
      <div class="card card-flush" :class="orgClassName">
        <div class="card-header pt-7">
          <h3 class="card-title align-items-start flex-column">
            <span class="card-label fw-bold text-gray-800">组织架构</span>
            <span class="fw-semibold fs-6 mt-1 text-gray-500">共 {{ departmentCount }} 个部门</span>
          </h3>
          <div class="card-toolbar">
            <a href="#" class="btn btn-sm btn-light" @click="fetchDepartmentTree">刷新</a>
          </div>
        </div>
        <div class="card-body scroll-y h-500px h-lg-500px pt-6">
          <div v-if="loading" class="text-center">
            <div class="spinner-border" role="status">
              <span class="sr-only">加载中...</span>
            </div>
          </div>
          <div v-else-if="error" class="alert alert-danger">
            {{ error }}
          </div>
          <div v-else class="table-responsive">
            <table class="table-row-dashed gs-0 gy-3 my-0 table align-middle">
              <thead>
                <tr class="fs-7 fw-bold border-bottom-0 text-gray-500">
                  <th class="min-w-175px p-0 pb-3 text-start">部门名称</th>
                </tr>
              </thead>
              <tbody>
                <template v-for="(item, i) in flatDepartments" :key="i">
                  <tr>
                    <td>
                      <a
                        href="#"
                        class="fw-bold text-hover-primary fs-6 mb-1 text-gray-800"
                        :style="{ paddingLeft: `${item.level * 20}px` }"
                        @click.prevent="handleSelect(item.dept.id)"
                        >{{ item.dept.name }}（{{ item.dept.engineerCount }}）</a
                      >
                    </td>
                  </tr>
                </template>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <!-- Add another column after the first one -->
    <div class="col-md-6 col-lg-6 col-xl-6 col-xxl-6 mb-md-5 mb-xl-10">
      <div class="card card-flush" :class="engClassName">
        <div class="card-header pt-7">
          <h3 class="card-title align-items-start flex-column">
            <span class="card-label fw-bold text-gray-800">工程师列表</span>
            <span class="fw-semibold fs-6 mt-1 text-gray-500">
              {{ selectedDeptName }} 共 {{ engineers.length }} 名工程师
            </span>
          </h3>
          <div class="card-toolbar">
            <button class="btn btn-sm btn-light-primary me-3" @click="fetchEngineers">刷新</button>
            <div class="form-check form-switch form-check-custom form-check-solid">
              <input
                id="filterNoCommits"
                v-model="filterNoCommits"
                class="form-check-input"
                type="checkbox"
              />
              <label class="form-check-label" for="filterNoCommits">过滤掉没有Git提交的人</label>
            </div>
          </div>
        </div>
        <div class="card-body scroll-y h-500px h-lg-500px pt-6">
          <div v-if="loadingEngineers" class="text-center">
            <div class="spinner-border" role="status">
              <span class="sr-only">加载中...</span>
            </div>
          </div>
          <div v-else-if="errorEngineers" class="alert alert-danger">
            {{ errorEngineers }}
          </div>
          <div v-else-if="engineers.length === 0" class="text-center text-gray-500">
            请选择一个部门
          </div>
          <div v-else class="engineer-list">
            <div
              v-for="engineer in filteredEngineers"
              :key="engineer.id"
              class="engineer-item bg-light mb-3 rounded border p-3"
            >
              <div class="d-flex align-items-center mb-2">
                <i class="ki-duotone ki-user fs-2 text-primary me-3"></i>
                <div>
                  <span class="fw-bold fs-5">{{ engineer.name }}</span>
                  <KTIcon
                    v-if="engineer.role"
                    :icon-name="roleSettings[engineer.role].icon"
                    :icon-class="`fs-5 text-${roleSettings[engineer.role].color} ms-2`"
                  />
                  <span
                    v-if="engineer.role"
                    :class="`badge badge-light-${roleSettings[engineer.role].color} ms-1`"
                  >
                    {{ roleSettings[engineer.role].name }}
                  </span>
                  <span v-if="engineer.emails.length > 0" class="badge badge-success ms-2">
                    有Git提交
                  </span>
                  <span v-else class="badge badge-warning ms-2">无Git提交</span>
                </div>
              </div>
              <div v-if="engineer.emails.length > 0" class="ms-5">
                <div
                  v-for="(email, index) in engineer.emails"
                  :key="index"
                  class="d-flex align-items-center mb-1 text-gray-600"
                >
                  <i class="ki-duotone ki-profile-user fs-6 me-2 text-gray-500"></i>
                  <span>{{ email.authorName }} ({{ email.email }})</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { getAssetPath } from '@/core/helpers/assets';
import { defineComponent, ref, onMounted, computed } from 'vue';
import { departmentService } from '@/services/business/department.service';
import { engineerService } from '@/services/business/engineer.service';
import { statisticsService } from '@/services/analysis/statistics.service';
import HistoricalTop5 from '@/components/analysis/HistoricalTop5.vue';
import LastMonthTop5 from '@/components/analysis/LastMonthTop5.vue';
import ActiveRepositoryTop10 from '@/components/analysis/ActiveRepositoryTop10.vue';
import { roleSettings } from '@/utils/roleUtils';
import ImportInfoWidget from '@/components/biz/ImportInfoWidget.vue';
import RepoCountWidget from '@/components/biz/RepoCountWidget.vue';
import CommitRepoWidget from '@/components/biz/CommitRepoWidget.vue';
import EngineerStatsWidget from '@/components/biz/EngineerStatsWidget.vue';
import DashboardIllustrationWidget from '@/components/biz/DashboardIllustrationWidget.vue';
import type { DepartmentTreeDTO } from '@/types/business/department';
import type { Engineer } from '@/types/business/engineer';
import type { BaseInfo } from '@/types/business/commit';

export default defineComponent({
  name: 'MainDashboard',
  components: {
    HistoricalTop5,
    LastMonthTop5,
    ActiveRepositoryTop10,
    ImportInfoWidget,
    RepoCountWidget,
    CommitRepoWidget,
    EngineerStatsWidget,
    DashboardIllustrationWidget,
  },
  setup() {
    const departmentTree = ref<DepartmentTreeDTO[]>([]);
    const loading = ref(true);
    const error = ref<string | null>(null);
    const departmentCount = ref(0);

    const selectedDeptId = ref('');
    const engineers = ref<Engineer[]>([]);
    const loadingEngineers = ref(false);
    const errorEngineers = ref<string | null>(null);

    const flatDepartments = ref<{ dept: DepartmentTreeDTO; level: number }[]>([]);

    const orgClassName = 'shadow-lg';
    const engClassName = 'shadow-lg';

    const selectedDeptName = ref('');

    const baseInfo = ref<
      BaseInfo & {
        beijingRepoCount: number;
        chengduRepoCount: number;
        reposWithCommits: number;
        reposWithCommitsLastMonth: number;
        totalEngineers: number;
        backendEngineers: number;
        frontendEngineers: number;
      }
    >({
      latestImportDate: null,
      beijingRepoCount: 0,
      chengduRepoCount: 0,
      reposWithCommits: 0,
      reposWithCommitsLastMonth: 0,
      totalCommits: 0,
      totalEngineers: 0,
      backendEngineers: 0,
      frontendEngineers: 0,
      currentMonthCommits: 0,
      previousMonthCommits: 0,
    });

    const fetchBaseInfo = async () => {
      try {
        baseInfo.value = (await statisticsService.getBaseInfo()) as BaseInfo & {
          beijingRepoCount: number;
          chengduRepoCount: number;
          reposWithCommits: number;
          reposWithCommitsLastMonth: number;
          totalEngineers: number;
          backendEngineers: number;
          frontendEngineers: number;
        };
      } catch (err) {
        console.error('Failed to fetch base info:', err);
      }
    };

    const flattenTree = (
      departments: DepartmentTreeDTO[],
      accumulator: { dept: DepartmentTreeDTO; level: number }[] = [],
      currentLevel: number = 0,
    ): { dept: DepartmentTreeDTO; level: number }[] => {
      departments.forEach((dep) => {
        accumulator.push({ dept: dep, level: currentLevel });
        if (dep.children && dep.children.length > 0) {
          flattenTree(dep.children, accumulator, currentLevel + 1);
        }
      });
      return accumulator;
    };

    const calculateDepartmentCount = (
      departments: { dept: DepartmentTreeDTO; level: number }[],
    ): number => {
      return departments.length;
    };

    const fetchDepartmentTree = async () => {
      try {
        loading.value = true;
        error.value = null;
        departmentTree.value = await departmentService.getDepartmentTree();
        flatDepartments.value = flattenTree(departmentTree.value);
        departmentCount.value = calculateDepartmentCount(flatDepartments.value);
      } catch (err) {
        console.error('Failed to fetch department tree:', err);
        error.value = '加载组织架构失败，请稍后重试';
      } finally {
        loading.value = false;
      }
    };

    // Recursive function to find dept name
    const findDeptName = (nodes: DepartmentTreeDTO[], id: string): string | null => {
      for (const node of nodes) {
        if (node.id === id) return node.name;
        if (node.children) {
          const found = findDeptName(node.children, id);
          if (found) return found;
        }
      }
      return null;
    };

    const handleSelect = (deptId: string) => {
      selectedDeptId.value = deptId;
      selectedDeptName.value = findDeptName(departmentTree.value, deptId) || '';
      fetchEngineers();
    };

    const fetchEngineers = async () => {
      if (!selectedDeptId.value) return;
      try {
        loadingEngineers.value = true;
        errorEngineers.value = null;
        engineers.value = await engineerService.getEngineersByDept(selectedDeptId.value);
      } catch (err) {
        console.error('Failed to fetch engineers:', err);
        errorEngineers.value = '加载工程师列表失败，请稍后重试';
      } finally {
        loadingEngineers.value = false;
      }
    };

    const filterNoCommits = ref(false);

    const filteredEngineers = computed(() => {
      return filterNoCommits.value
        ? engineers.value.filter((e) => e.emails.length > 0)
        : engineers.value;
    });

    onMounted(() => {
      fetchDepartmentTree();
      fetchBaseInfo();
    });

    return {
      getAssetPath,
      departmentTree,
      loading,
      error,
      fetchDepartmentTree,
      selectedDeptId,
      engineers,
      loadingEngineers,
      errorEngineers,
      handleSelect,
      fetchEngineers,
      departmentCount,
      orgClassName,
      engClassName,
      flatDepartments,
      selectedDeptName,
      findDeptName,
      roleSettings,
      filterNoCommits,
      filteredEngineers,
      baseInfo,
    };
  },
});
</script>

<style scoped>
.department-tree,
.engineer-list {
  max-height: unset;
  overflow-y: unset;
}

.department-node {
  margin-bottom: 0.5rem;
}

.engineer-item {
  transition: box-shadow 0.3s ease;
}

.engineer-item:hover {
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}
</style>
